package com.jinduplan.planmanager.ui.activity.clockin

import android.app.Dialog
import android.content.Intent
import android.graphics.Bitmap
import android.text.Editable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.cxz.kotlin.baselibs.adapter.ViewHolder
import com.cxz.kotlin.baselibs.base.BaseMvpTitleActivity
import com.cxz.kotlin.baselibs.base.setTextChageListener
import com.cxz.kotlin.baselibs.utils.GsonHelper
import com.cxz.kotlin.baselibs.utils.LogUtil
import com.cxz.kotlin.baselibs.utils.Preference
import com.fphoenixcorneae.util.toast.ToastUtil
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.jinduplan.planmanager.R
import com.jinduplan.planmanager.bean.*
import com.jinduplan.planmanager.constant.Constant
import com.jinduplan.planmanager.mvp.contract.ClockInContract
import com.jinduplan.planmanager.mvp.presenter.ClockInPresenter
import com.jinduplan.planmanager.utils.CustomRecyclerFilterableAdapter
import com.jinduplan.planmanager.utils.ResUtil
import com.jinduplan.planmanager.widgets.MapClickInDialog
import kotlinx.android.synthetic.main.activity_clock_in.*
import kotlinx.android.synthetic.main.activity_clock_in.bmapView
import java.util.HashSet
import kotlin.collections.ArrayList


class ClockInActivity : BaseMvpTitleActivity<ClockInContract.View, ClockInContract.Presenter>(),
    ClockInContract.View {


    private var typeDialog: Dialog? = null
    private var province = ""
    private var city = ""
    private var distict = ""

    var project_addr: String by Preference(Constant.PROJECT_ADDR, "")


    var mProjectId: String by Preference(Constant.PROJECTID, "")
    var mProjiectName: String by Preference(Constant.PROJECT_NAME, "")


    var mLatitude = 0.toDouble()
    var mLongitude = 0.toDouble()
    var mAddr = ""
    var location:MyLocationData? = null
    var mBitmap:Bitmap? = null
    val clockDialog:MapClickInDialog by lazy {
        MapClickInDialog(this,mAddr,object:SelectCallback(){
            override fun onResult(photos: ArrayList<Photo>?, isOriginal: Boolean) {
                goActivity(ClockInComfirActivity::class.java, arrayListOf(Constant.CLOCK_IN_IMG),
                    arrayListOf(photos?.get(0)?.path))

            }

            override fun onCancel() {

            }

        })
    }
    override fun attachChildLayoutRes(): Int {
        return R.layout.activity_clock_in
    }

    override fun createPresenter(): ClockInContract.Presenter {
        return ClockInPresenter()
    }

    override fun start() {
        setBaseTitle(ResUtil.getS(R.string.project_positioning))
        val mlocdata = intent.extras?.getString(Constant.LOCDATA)
        intent.extras?.getString(Constant.PROVINCE)?.let {
            province = it
        }
        intent.extras?.getString(Constant.CITY)?.let {
            city = it
        }
        intent.extras?.getString(Constant.DISTRICT)?.let {
            distict = it
        }
        location = GsonHelper.parse(mlocdata, MyLocationData::class.java)
        bmapView.map.setMyLocationData(location)
        mLatitude = location?.latitude!!
        mLongitude = location?.longitude!!
        setMapLL(mLatitude,mLongitude)
        val addr = intent.extras?.getString(Constant.ADDR)
        tvDetail.setText(project_addr)
        tvLocation.setText("当前定位:${addr}")
        val poiname = intent.extras?.getString(Constant.POINAME)
        mAddr = "$addr$poiname"

        etName.setText(mProjiectName)
        tvDetail.setTextChageListener{

        }
        tvClockIn.setOnClickListener {
            LogUtil.d("tvClockIn!!!")
            mPresenter?.getProjectUploadDetailList(mProjectId.toInt())
//            showTypeDialog(2)
//            bmapView.map.snapshot {
//                mBitmap?.recycle()
//                clockDialog.setBitMap(WeakReference<Bitmap>(it)).show()
//                mBitmap = it
//            }
//            TipsDialog(this).setContent(ResUtil.getS(R.string.corrupt_tips)).show()
        }
    }

    override fun onResume() {
        bmapView.onResume()
        super.onResume()

    }

    override fun onPause() {
        bmapView.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        mBitmap?.recycle()
        if (null != bmapView) {
            bmapView.onDestroy()
        }
        super.onDestroy()
    }
    private fun setMapLL(latitude: Double, longitude: Double) {

        val mBaiduMap: BaiduMap = bmapView.getMap()
        mBaiduMap.mapType = BaiduMap.MAP_TYPE_NORMAL
        mBaiduMap.isMyLocationEnabled = true
        val bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.home_move)
        val point = LatLng(latitude, longitude)
        val option: OverlayOptions = MarkerOptions()
            .position(point)
            .icon(bitmap)
        mBaiduMap.addOverlay(option)
        bitmap.recycle()
        val ll = LatLng(latitude,longitude )
        val builder = MapStatus.Builder()
        builder.target(ll).zoom(18.0f)
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 8) {
            data?.let {
                val poinName = it.getStringExtra(Constant.POINAME)
                val addr = it.getStringExtra(Constant.ADDR)
                mAddr = "$addr$poinName"
                tvDetail.setText(addr)
                etName.setText(poinName)
                val latitude = it.getDoubleExtra(Constant.LATITUDE,0.toDouble())
                val longitude = it.getDoubleExtra(Constant.LONGITUDE,0.toDouble())

                mLatitude = latitude
                mLongitude = longitude
                setMapLL(latitude,longitude)

            }
        }
    }

    override fun clockInSuccess() {

    }

    override fun uploadPicSuccess() {

    }

    override fun uploadPicSuccess(picUrl: String) {

    }

    override fun postProjectLocationSuccess(uploadProjectLocation: UploadProjectLocation) {
        ToastUtil.show("上传定位成功")
        this.finish()
    }

    override fun setProjectUploadDetailListData(bean: BuildingNameBean) {


        showTypeDialog(bean.data)
    }



    //去重
    private fun removeListDuplicate(list: ArrayList<Any>): ArrayList<Any> {
        val h = HashSet(list)
        list.clear()
        list.addAll(h)
        return list
    }


    private fun showTypeDialog(data: ArrayList<BuildingsBean>) {
        typeDialog = Dialog(this, R.style.BottomDialog)
        val contentView: View =
            LayoutInflater.from(this).inflate(R.layout.dialog_project_upload_detail, null)
        typeDialog!!.setContentView(contentView)
        val layoutParams: ViewGroup.LayoutParams = contentView.layoutParams
        layoutParams.width = resources.displayMetrics.widthPixels
        contentView.layoutParams = layoutParams
        typeDialog!!.setCanceledOnTouchOutside(true)

        typeDialog!!.window?.setGravity(Gravity.BOTTOM)
        typeDialog!!.window?.setWindowAnimations(R.style.BottomDialog_Animation)
        typeDialog!!.show()
        typeDialog!!.findViewById<ImageView>(R.id.iv_close)
            .setOnClickListener {

                typeDialog!!.dismiss()
            }


        val recyclerView = typeDialog!!.findViewById<RecyclerView>(R.id.recyclerView)

        recyclerView.adapter = object : CustomRecyclerFilterableAdapter<BuildingsBean>(
            this, R.layout.item_rv_choose, data
        ) {
            override fun convert(holder: ViewHolder?, t: BuildingsBean, position: Int) {

                val textName = holder?.getView<TextView>(R.id.tv_name)
                textName?.text = t?.building_name
                textName?.isSelected = t?.isSelect == true
                holder?.setVisible(R.id.iv_choose, t?.isSelect == true)
                holder?.convertView?.setOnClickListener {
                    typeDialog?.dismiss()
                    mPresenter?.postProjectLocation(
                        mProjectId,
                        etName.text.toString(),
                        tvDetail.text.toString(),
                        mLatitude.toString(),
                        mLongitude.toString(),
                        t.id.toString(),
                        province,
                        city,
                        distict,
                        mAddr
                    )


                }
            }
        }
        typeDialog!!.findViewById<EditText>(R.id.ed_search).addTextChangedListener(object :
            android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                (recyclerView.adapter as CustomRecyclerFilterableAdapter<Any>).filter.filter(s.toString())
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        recyclerView.layoutManager = LinearLayoutManager(this)
    }

}